// 基础请求URL
const BASE_URL = 'http://localhost:9001/api'; // 后端API地址

// 获取存储的token
const getToken = () => {
  return uni.getStorageSync('token') || '';
};

// 刷新token方法
const refreshToken = () => {
  return new Promise((resolve, reject) => {
    const refreshToken = uni.getStorageSync('refreshToken');
    if (!refreshToken) {
      reject(new Error('没有刷新令牌'));
      return;
    }
    
    uni.request({
      url: `${BASE_URL}/user/refresh-token`,
      method: 'POST',
      data: { refreshToken },
      success(res) {
        if (res.data.code === 1 && res.data.data.token) {
          uni.setStorageSync('token', res.data.data.token);
          resolve(res.data.data.token);
        } else {
          reject(new Error('刷新令牌失败'));
        }
      },
      fail(err) {
        reject(err);
      }
    });
  });
};

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = getToken();
    const header = options.header || {};
    
    // 添加认证头
    if (token) {
      header.Authorization = `Bearer ${token}`;
    }
    
    uni.request({
      url: options.url.indexOf('http') === 0 ? options.url : `${BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data,
      header,
      success(res) {
        // 处理401未授权错误（令牌过期）
        if (res.statusCode === 401) {
          // 尝试刷新令牌
          refreshToken()
            .then(newToken => {
              // 使用新令牌重试请求
              options.header = options.header || {};
              options.header.Authorization = `Bearer ${newToken}`;
              request(options).then(resolve).catch(reject);
            })
            .catch(err => {
              // 刷新失败，需要重新登录
              uni.removeStorageSync('token');
              uni.removeStorageSync('refreshToken');
              uni.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none'
              });
              uni.navigateTo({
                url: '/pages/login/index'
              });
              reject(err);
            });
        } else if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(res);
        }
      },
      fail(err) {
        reject(err);
      }
    });
  });
};

export default {
  get: (url, data, options = {}) => request({ url, data, method: 'GET', ...options }),
  post: (url, data, options = {}) => request({ url, data, method: 'POST', ...options }),
  put: (url, data, options = {}) => request({ url, data, method: 'PUT', ...options }),
  delete: (url, data, options = {}) => request({ url, data, method: 'DELETE', ...options })
}; 